<template>
    <nly-content-wrapper>
        <nly-content style="margin-top: 42px;">
            <a-tabs @change="tabChange" style="border:1px solid #ccc;">
                <a-tab-pane key="1" tab="产品" style="height:calc(100vh - 152px);overflow-y:auto;">
                    <a-row :span="24" style="margin-top: 20px; ">
                        <a-col class="goods-box" :lg="12" :xl="8" :xxl="6" v-for="(item, index) in data" :key="index">
                            <div class="gutter-box">
                                <div class="gutter-img">
                                    <img :src="item.goodsLogoUrl" />
                                </div>
                                <div class="gutter-title">
                                    <label>{{item.goodsName}}</label>
                                </div>
                                <div style="flex:0 0 100%;margin-top:20px;text-align:left">
                                    <h3>产品简介</h3>
                                </div>
                                <div style="flex:0 0 100%;margin-top:20px;text-align:left;height:60px;overflow:hidden">
                                    <div v-html="item.remarks"></div>
                                </div>
                                <ul class="googs-ul">
                                    <li>用户数量：{{item.users}}</li>
                                    <li>商品价格：￥{{item.price}}</li>
                                    <li>
                                        使用年限：
                                        <select @change="useYearChang($event, item)">
                                            <option v-for="(year, index) in config" :key="index" :value="year.years">{{year.years}}年</option>
                                        </select>
                                    </li>
                                    <li>商品折扣：{{item.discountRate ? item.discountRate : config.find(f => f.years == item.years) && config.find(f => f.years == item.years).discountRate}}</li>
                                    <li>支付金额：￥{{item.salePrice ? item.salePrice : parseFloat(item.price) * parseFloat(item.discountRate ? item.discountRate : config.find(f => f.years == item.years) && config.find(f => f.years == item.years).discountRate) * 0.01}}
                                    </li>
                                </ul>
                                <div class="buy-div" style="background: #ff6b00;color:#FFFFFF" v-if="userInfo_temp.goodsId == item.id">
                                    正在使用...
                                </div>
                                <div class="buy-div color-text" v-else @click="useGoods(item)">立即试用</div>
                                <div class="buy-div" style="margin-left:50px" @click="buyGoods(item)">立即购买</div>
                                <!-- <div v-if="item.copyright" class="copyright-box">{{item.copyright}} 版权所有</div> -->
                                <div class="copyright-box-null">&nbsp;</div>
                            </div>
                        </a-col>
                        <!-- <a-col class="goods-box" :span="8" v-for="(item, index) in data" :key="index">
                            <div class="gutter-box">
                                <div style="margin-top: 10px;">
                                    <img src="@/assets/image/order.png" />
                                </div>
                                <div>
                                    <label>{{item.goodsName}}</label>
                                </div>
                                <ul class="googs-ul">
                                    <li>用户数量：{{item.users}}</li>
                                    <li>商品价格：￥{{item.price}}</li>
                                    <li>
                                        使用年限：
                                        <select @change="useYearChang($event, item)">
                                            <option v-for="(year, index) in config" :key="index" :value="year.years">{{year.years}}年</option>
                                        </select>
                                    </li>
                                    <li>商品折扣：{{item.discountRate ? item.discountRate : config.find(f => f.years == item.years) && config.find(f => f.years == item.years).discountRate}}</li>
                                    <li>支付金额：￥{{item.salePrice ? item.salePrice : parseFloat(item.price) * parseFloat(item.discountRate ? item.discountRate : config.find(f => f.years == item.years) && config.find(f => f.years == item.years).discountRate) * 0.01}}
                                    </li>
                                </ul>
                                <div class="buy-div" @click="buyGoods(item)">购买</div>
                            </div>
                        </a-col> -->
                    </a-row>
                </a-tab-pane>
            </a-tabs>
            <drag-modal v-model="buyVisible" title="订单确认" centered on-ok="handleok" @cancel="() => {this.buyVisible = false}" width="500px">
                <div class="line" style="font-size:15px;margin-bottom:10px;">
                    <span style="color:#1980Ff;">账户余额：</span>{{accountData.balance || "0.00"}} 元
                    <div style="float:right;cursor:pointer">
                        <a-button type="primary" ghost @click="()=>{this.operationModal = true}">充值</a-button>
                    </div>
                </div>
                <div class="line" style="color:#1980Ff;font-size:15px;">商品信息</div>
                <div id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="商品名称">{{goodsInfo.goodsName}}</a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="用户数量">
                                    {{goodsInfo.users}}
                                    <!-- <a-input-number id="inputNumber" v-model="goodsInfo.users" :min="5" @change="goodsChange" :disabled="true" /> -->
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="使用年限">
                                    <div class="number-box-aaaaaaaa">
                                        <a-input-number style="width:40px" id="inputNumber" v-model="goodsInfo.years" :min="1" :max="9" @change="goodsChange" />
                                    </div>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="折扣">{{goodsInfo.discountRate}}</a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="商品原价">￥{{goodsInfo.price}}</a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="实际支付">￥{{goodsInfo.salePrice}}</a-form-item>
                            </a-col>
                        </a-row>
                        <!-- <a-row :gutter="24">
                            <a-col :span="22" :pull="3">
                                <a-form-item label="产品简介">
                                    <div v-html="goodsInfo.remarks">

                                    </div>
                                </a-form-item>
                            </a-col>
                        </a-row> -->
                    </a-form>
                    <div class="line" style="color:#1980Ff;font-size:15px;">支付条款</div>
                    <div style="margin-left: 21px;">
                        <a-checkbox v-model="agreeCheck">
                            <span>本商品一旦出售，将不能退款</span>
                        </a-checkbox>
                    </div>

                    <!-- <div class="line" style="color:#1980Ff;font-size:15px;margin-top:30px;">支付方式</div>
                    <div style="margin-top:20px;margin-left:50px;">
                        <a-radio-group v-model="payMethod">
                            <a-radio :value="1">
                                <img src="@/assets/image/alipay.png" />
                            </a-radio>
                            <a-radio :value="2">
                                <img src="@/assets/image/wxpay.png" style="height: 25px;" />
                            </a-radio>
                        </a-radio-group>
                    </div> -->
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" @click="pay">立即购买</a-button>
                    <a-button key="back" @click="() => (buyVisible = false)">取消</a-button>
                </template>
            </drag-modal>

            <!--充值弹窗-->
            <drag-modal class="research-drag-wrapper" v-model="operationModal" title="账户充值" @cancel="cancel" width="400px">
                <a-descriptions :title="false" :column="1">
                    <a-descriptions-item label="账户余额">
                        <span style="font-weight:bold">{{accountData.balance}}</span>元
                    </a-descriptions-item>
                    <a-descriptions-item label="充值金额">
                        <a-input size="small" v-model="amount" oninput="value=value.toString().match(/^\d+(?:\.\d{0,2})?/)" maxLength="10" style="width:200px">
                            <a-select slot="addonAfter" default-value="1" v-model="payMethod" style="width: 130px">
                                <a-select-option :value="1" style="olor:#1578FF">
                                    <a-icon type="alipay-circle" style="color:#1578FF" /> 支付宝支付
                                </a-select-option>
                                <a-select-option :value="2" style="color:#42B035">
                                    <a-icon type="wechat" style="color:#42B035" /> 微信支付
                                </a-select-option>
                            </a-select>
                        </a-input>
                    </a-descriptions-item>
                    <!-- <a-descriptions-item label="我已了解">
                        <a-checkbox v-model="agreeCheck">
                            <span style="color:red">充值金额，仅限外呼功能模块消费</span>
                        </a-checkbox>
                    </a-descriptions-item> -->
                </a-descriptions>
                <template slot="footer">
                    <a-button type="primary" @click="createPayOrder">确认充值</a-button>
                    <a-button @click="cancel" class="margin-left-10">取消</a-button>
                </template>
            </drag-modal>
            <!-- 微信支付 -->
            <a-modal v-model="wxPayVisible" title="微信支付" centered on-ok="handleok" @cancel="()=>{this.wxPayVisible = false}" width="800px">
                <div>
                    <!-- <span>应付金额2599.00元</span>  -->
                </div>
                <div style="margin-top: 20px;">
                    <img style="margin-left: 40px; height: 250px; width: 250px" :src="payCodeImg" />
                    <img style="margin-left: 40px; height: 300px;" src="@/assets/image/pc_icon_phone-bg.png" />
                </div>
                <template slot="footer">
                    <a-button key="back" @click="() => (wxPayVisible = false)">取消</a-button>
                </template>
            </a-modal>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import { listToMap } from "@/utils/tool/map";
import { mapState } from "vuex";
import { components } from "@/utils/antTableComponents";
import { pageList, useGoods } from "@/api/member/goods";
import { createPayOrder } from "@/api/expenses/paymentOrder";
import {  getAliPayUrlFromPayment, getWeXinPayImageFromPayOrder } from "@/api/member/order";

import { configList } from "@/api/member/config";
import { getOrderDetail, deleteOrder, aliPay, wxPay, saveOrder } from "@/api/member/order";
import { getByCompany } from "@/api/expenses/expensesAccount";

const basePostData = {
    current: 1,
    size: 20,
    goodsType: 'software'//商品分类 软件 software 话费 telCharges"
};

export default {
    data () {
        return {
            accountData: {
                balance: 0.00
            },                    //账户余额
            orderId: "",
            orderPayVisible: false,
            wxPayVisible: false,
            tabKey: 1,
            postData: { ...basePostData },
            data: [],
            buyVisible: false, //购买商品弹窗
            goodsInfo: {},
            discountRate: 0,
            payCodeImg: "",
            config: [],

            operationModal: false,//新增修改弹窗
            amount: null,//充值金额
            agreeCheck: true,//支付条款
            payMethod: 1,            //支付方式
        };
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            userInfo_temp: state => state.user.info,
            permissions: state => state.user.permissions,
        })
    },
    activated () {
        this.reloadData();
    },
    methods: {
        cancel () {
            this.operationModal = false;
        },
        reloadData () {
            this.getConfigList();
            this.PageList();
            this.getAccount();
        },
        //获取账户余额
        getAccount () {
            getByCompany().then(response => {
                if (response.code === 200) {
                    if(response.data){
                        this.accountData = response.data;
                    }
                    console.log("获取账户余额", this.accountData);
                }
            });
        },
        //tab 切换
        tabChange (key) {
            console.log(key);
            this.tabKey = key;
            this.PageList();
        },
        //商品配置
        getConfigList () {
            configList().then(response => {
                if (response.code == 200) {
                    this.config = response.data;
                    console.log(this.config);
                }
            });
        },
        //获取商品列表
        PageList () {
            const { postData } = this;
            pageList(postData).then(response => {
                if (response.code === 200) {
                    // const { data } = response;
                    // const { records, total, current, size } = data;
                    this.data = response.data;
                }
            }).catch(error => { });
        },
        //创建支付订单
        createPayOrder () {
            if (!this.amount || this.amount == 0) {
                this.$message.warning('请输入金额');
                return;
            }
            // if (!this.agreeCheck) {
            //     this.$message.warn("请同意支付条款");
            //     return;
            // }
            if (!this.payMethod) {
                this.$message.warn("请选择支付方式");
                return;
            }
            createPayOrder({ amount: this.amount }).then(response => {
                if (response.code == 200) {
                    let { id, orderNo } = response.data;
                    if (this.payMethod == 1) { //支付宝支付
                        getAliPayUrlFromPayment({
                            orderId: id,           //支付订单ID
                        }).then(response => {
                            this.gotoPayUrl(response);
                        });
                    } else { //微信支付
                        getWeXinPayImageFromPayOrder({
                            orderId: id
                        }).then(response => {
                            console.log(response);
                            this.payCodeImg = response.data;
                            this.wxPayVisible = true;
                            let wxPayInterval = window.setInterval(() => {
                                setTimeout(this.wxPayResult(wxPayInterval, orderId), 0);
                            }, 5000)
                        });
                    }
                }
            });
        },
        gotoPayUrl (response) {
            var win = window.open("", "支付");
            win.document.open();
            win.document.write(response);
            win.document.close();
            this.orderPayVisible = false;
            this.wxPayVisible = false;
            this.buyVisible = false;
        },
        //微信支付结果
        wxPayResult (wxPayInterval, orderId) {
            console.log("==============请求成功==============");
            getOrderDetail({ orderId: orderId }).then(res => {
                if (res.code == 200) {
                    if (res.data.orderStatus == 1) {
                        this.$message.success("支付成功");
                        this.orderPayVisible = false;
                        this.wxPayVisible = false;
                        this.buyVisible = false;
                        this.$router.push(`/views/system/order/list`)
                        clearInterval(wxPayInterval);
                    }
                } else {
                    clearInterval(wxPayInterval);
                }
            });
        },
        //获取订单
        buyGoods (data) {
            this.goodsInfo = { ...data };
            this.changeRate();
            this.buyVisible = true;
            if (this.goodsInfo.discountRate) {
                this.goodsInfo.salePrice = this.goodsInfo.price * this.goodsInfo.years * ((this.goodsInfo.discountRate) * 0.01);
            }
        },
        //商品购买价钱
        goodsChange (value) {
            this.changeRate();
            this.goodsInfo.salePrice = (this.goodsInfo.price * this.goodsInfo.years * ((this.goodsInfo.discountRate) * 0.01)).toFixed(2);
        },
        //购买商品支付
        pay () {
            console.log("商品支付", this.agreeCheck, this.payMethod, this.goodsInfo);
            if (!this.agreeCheck) {
                this.$message.warn("请同意支付条款");
                return;
            }

            // if (!this.payMethod) {
            //     this.$message.warn("请选择支付方式");
            //     return;
            // }

            this.goodsInfo.createDate = null;
            this.goodsInfo.goodsId = this.goodsInfo.id;
            this.goodsInfo.orderType = 1;
            this.goodsInfo.orderBusinessType = "Goods";
            saveOrder(this.goodsInfo).then(response => {
                if (response.code == 200) {
                    this.$message.success("购买成功");
                    this.wxPayVisible = false;
                    this.buyVisible = false;
                    this.reloadData();
                    this.$router.push(`/views/system/info/companyInfo`);
                    // let orderId = response.data.id;
                    // if (this.payMethod == 1) { //支付宝支付
                    //     aliPay({
                    //         orderId: orderId,
                    //         subjectName: response.data.goodsName
                    //     }).then(response => {
                    //         this.gotoPayUrl(response);
                    //     });
                    // } else { //微信支付
                    //     wxPay({
                    //         orderId: orderId
                    //     }).then(response => {
                    //         console.log(response);
                    //         this.payCodeImg = response.data;
                    //         this.wxPayVisible = true;
                    //         let wxPayInterval = window.setInterval(() => {
                    //             setTimeout(this.wxPayResult(wxPayInterval, orderId), 0);
                    //         }, 5000)
                    //     });
                    // }
                }
            });
        },
        //改变折扣
        changeRate () {
            this.goodsInfo.discountRate = 0;
            if (this.config.length > 0 && this.goodsInfo.years > 0) {
                let config = this.config.find(f => f.years == this.goodsInfo.years);
                console.log(config)
                if (config != null) {
                    this.goodsInfo.discountRate = config.discountRate;
                } else {
                    this.goodsInfo.discountRate = this.config[this.config.length - 1].discountRate;
                }
            }
            console.log('_____进方法了————————', this.goodsInfo.discountRate)
        },
        //商品列表改变年限
        useYearChang (e, item) {
            item.years = e.target.value;
            item.discountRate = this.config.find(f => f.years == item.years).discountRate;
            item.salePrice = (parseFloat(item.years) * parseFloat(item.price) * parseFloat(item.discountRate) * 0.01).toFixed(2);
            // console.log(item.salePrice)
        },
        useGoods (item) {
            //开始使用产品
            useGoods({ id: item.id }).then(res => {
                if (res.code === 200) {
                    this.$message.success('使用成功');
                    window.location.reload();
                }
            })
        }
    },
    watch: {}
};
</script>
<style lang="scss" scoped>
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .ant-advanced-search-form {
        padding: 0px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    .goods-box {
        margin-bottom: 20px;
    }
    .goods-box:hover {
        .gutter-box {
            border: 1px solid #ff6b00;
        }
    }
    .gutter-box {
        display: flex;
        flex-wrap: wrap;
        margin: 0 auto;
        border: 1px solid #bfbfbf;
        padding: 20px;
        max-width: 320px;
        text-align: center;
        background-image: url(~@/assets/goods_background.jpg);
        background-repeat: no-repeat;
        background-size: contain;
    }

    .copyright-box,
    .copyright-box-null {
        color: #373d41;
        background: #f9e6d8;
        line-height: 40px;
        text-align: center;
        max-width: 420px;
        margin: 0 auto;
        border-top: 0px;
    }
    .copyright-box-null {
        background: #ffffff;
    }
    .gutter-title {
        flex: 0 0 60%;
        color: #373d41;
        height: 72px;
        overflow: hidden;
        font-size: 22px;
        text-align: left;
        font-weight: bold;
    }
    .googs-ul {
        width: 420px;
        text-align: left;
        padding-left: 0;
        margin-left: 10px;
        margin-top: 10px;
        list-style: none;
    }
    .googs-ul li::before {
        content: '● ';
        color: #ff6b00;
    }

    .buy-div {
        flex: 0 0 40%;
        height: 38px;
        background: #00a0e9;
        margin: auto;
        letter-spacing: 2px;
        text-align: center;
        line-height: 38px;
        color: #f2f2f2;
        font-size: 16px;
        cursor: pointer;
        margin-top: 10px;
        &.color-text {
            background: #52c41a;
        }
    }
    .first-tit {
        .i-tit {
            text-align: left;
            font-size: 16px;
            font-weight: 700;
            line-height: 16px;
            color: #60666b;
            padding-bottom: 10px;
            border-bottom: 1px dashed #ccc;
            .module-wrap p {
                margin: 0;
                padding: 0;
            }
        }
        .goods-li {
            vertical-align: middle;
            color: rgba(71, 78, 83, 0.8);
            height: 160px;
            overflow-y: auto;
            text-align: left;
        }
    }
    .gutter-img {
        flex: 0 0 40%;
        height: 100px;
        img {
            width: 80px;
            height: 80px;
            border-radius: 12px;
        }
    }
</style>

<style lang="less">
    .number-box-aaaaaaaa {
        .ant-input-number-handler-wrap {
            display: block !important;
        }
    }
</style>
